package cn.yueranzs.login.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.yueranzs.response.ResultCode;
import cn.yueranzs.response.UserResultCode;
import cn.yueranzs.system.pojo.Menu;
import cn.yueranzs.system.pojo.Role;
import cn.yueranzs.system.pojo.User;
import cn.yueranzs.system.service.UserService;
import cn.yueranzs.utils.MenuUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yueranzs
 * @date 2021/12/1 11:38
 */
@Component
public class LoginUserDetails implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getOne(new QueryWrapper<User>().lambda().select(User::getId,User::getUsername, User::getPassword)
                .eq(User::getUsername, username)
                .eq(User::getDeleted, ResultCode.NODELETE.getCode()));
        if (ObjectUtil.isNull(user)) {
            //用户不存在
            throw new InternalAuthenticationServiceException(UserResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        //查询角色
        List<Role> roles = userService.getRolesByUserId(user.getId());
        Set authorities = new HashSet();
        roles.forEach(role -> authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName())));
        user.setAuthorities(authorities);

        //查询菜单
        List<Menu> menusByRoleIds = userService.getMenusByRoleIds(roles.stream().map(Role::getId).collect(Collectors.toList()));
        user.setMenus(MenuUtil.getMenus(menusByRoleIds));
        return user;
    }
}
